<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    
    <title>静谧的生命时钟 - 人生倒计时</title>
    <meta name="description" content="静谧的生命时钟，用优雅的方式展示时间的流逝，珍惜每一刻人生时光。">
    <meta name="keywords" content="人生倒计时,生命时钟,时间管理,人生规划">
    
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- 图标 -->
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><text y='20' font-size='20'>⏰</text></svg>">
    
    <style>
        /* CSS变量定义 */
        :root {
            --bg-primary: #0a192f;
            --bg-overlay: rgba(10, 25, 47, 0.85);
            --text-primary: #ffffff;
            --text-secondary: rgba(255, 255, 255, 0.8);
            --text-accent: #64ffda;
            --gradient-primary: linear-gradient(135deg, #ff6b35 0%, #f7931e 25%, #ffd23f 50%, #06ffa5 75%, #4dabf7 100%);
            --gradient-secondary: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
            --glass-bg: rgba(255, 255, 255, 0.1);
            --glass-border: rgba(255, 255, 255, 0.2);
            --shadow-glow: 0 0 30px rgba(100, 255, 218, 0.3);
            --shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3);
        }

        /* 基础重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: var(--bg-primary);
            color: var(--text-primary);
            min-height: 100vh;
            overflow-x: hidden;
            position: relative;
        }

        /* 星空背景 */
        .starry-background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(2px 2px at 20px 30px, #eee, transparent),
                radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
                radial-gradient(1px 1px at 90px 40px, #fff, transparent),
                radial-gradient(1px 1px at 130px 80px, rgba(255,255,255,0.6), transparent),
                radial-gradient(2px 2px at 160px 30px, #ddd, transparent),
                var(--bg-primary);
            background-repeat: repeat;
            background-size: 200px 100px;
            animation: twinkle 4s ease-in-out infinite alternate;
            z-index: -2;
        }

        .background-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: var(--bg-overlay);
            z-index: -1;
        }

        @keyframes twinkle {
            0% { opacity: 0.8; }
            100% { opacity: 1; }
        }

        /* 主容器 */
        .app-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
            position: relative;
        }

        /* 设置按钮 */
        .settings-btn {
            position: fixed;
            top: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            border: 1px solid var(--glass-border);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .settings-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: rotate(90deg);
            box-shadow: var(--shadow-glow);
        }

        .settings-btn svg {
            width: 24px;
            height: 24px;
            fill: var(--text-primary);
        }

        /* 主要内容区域 */
        .main-content {
            text-align: center;
            max-width: 1200px;
            width: 100%;
        }

        /* 标题区域 */
        .title-section {
            margin-bottom: 60px;
        }

        .app-title {
            font-size: clamp(2.5rem, 5vw, 4rem);
            font-weight: 300;
            margin-bottom: 20px;
            background: var(--gradient-primary);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .app-subtitle {
            font-size: 1.2rem;
            color: var(--text-secondary);
            font-weight: 300;
            margin-bottom: 10px;
        }

        .quote-section {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-top: 15px;
        }

        .quote {
            font-size: 1rem;
            color: var(--text-accent);
            font-style: italic;
            font-weight: 300;
            transition: opacity 0.3s ease;
            flex: 1;
            max-width: 600px;
        }

        .refresh-quote-btn {
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            border: 1px solid var(--glass-border);
            border-radius: 50%;
            width: 35px;
            height: 35px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
            color: var(--text-secondary);
        }

        .refresh-quote-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: rotate(180deg);
            box-shadow: var(--shadow-glow);
        }

        .refresh-quote-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* 圆形进度环 */
        .progress-ring-container {
            position: relative;
            margin: 60px auto;
            width: 300px;
            height: 300px;
        }

        .progress-ring {
            width: 100%;
            height: 100%;
            transform: rotate(-90deg);
        }

        .progress-ring-bg {
            fill: none;
            stroke: rgba(255, 255, 255, 0.1);
            stroke-width: 8;
        }

        .progress-ring-fill {
            fill: none;
            stroke: url(#progressGradient);
            stroke-width: 8;
            stroke-linecap: round;
            transition: stroke-dasharray 1s ease-in-out;
            filter: drop-shadow(0 0 10px rgba(100, 255, 218, 0.5));
        }

        .progress-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .progress-label {
            font-size: 1rem;
            color: var(--text-secondary);
            margin-bottom: 10px;
            font-weight: 300;
        }

        .progress-percentage {
            font-size: 3.5rem;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 10px;
            text-shadow: 0 0 20px rgba(100, 255, 218, 0.5);
        }

        .progress-sublabel {
            font-size: 0.9rem;
            color: var(--text-accent);
            font-weight: 300;
        }

        /* 剩余时间显示 */
        .remaining-time {
            margin: 40px 0;
        }

        .remaining-number {
            font-size: clamp(3rem, 8vw, 6rem);
            font-weight: 700;
            color: var(--text-primary);
            margin-bottom: 20px;
            text-shadow: 0 0 30px rgba(255, 255, 255, 0.3);
        }

        .unit-switcher {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .unit-btn {
            padding: 8px 16px;
            background: var(--glass-bg);
            backdrop-filter: blur(10px);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9rem;
            font-weight: 400;
        }

        .unit-btn.active {
            background: var(--gradient-secondary);
            color: var(--text-primary);
            box-shadow: var(--shadow-glow);
        }

        .unit-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        /* 倒计时卡片网格 */
        .countdown-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 60px;
        }

        .countdown-card {
            background: var(--glass-bg);
            backdrop-filter: blur(15px);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 25px;
            text-align: center;
            transition: all 0.3s ease;
            box-shadow: var(--shadow-card);
        }

        .countdown-card:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.15);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
        }

        .card-icon {
            font-size: 2rem;
            margin-bottom: 15px;
        }

        .card-title {
            font-size: 1.1rem;
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: 15px;
        }

        .card-progress {
            width: 100%;
            height: 4px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
            margin: 15px 0;
            overflow: hidden;
        }

        .card-progress-fill {
            height: 100%;
            background: var(--gradient-primary);
            border-radius: 2px;
            transition: width 1s ease-in-out;
        }

        .card-number {
            font-size: 1.8rem;
            font-weight: 600;
            color: var(--text-accent);
            margin-bottom: 5px;
        }

        .card-unit {
            font-size: 0.9rem;
            color: var(--text-secondary);
            font-weight: 300;
        }

        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(10px);
            z-index: 2000;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 40px;
            max-width: 500px;
            width: 90%;
            text-align: center;
            box-shadow: var(--shadow-card);
        }

        .modal-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin-bottom: 30px;
            color: var(--text-primary);
        }

        .form-group {
            margin-bottom: 25px;
            text-align: left;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            color: var(--text-secondary);
            font-weight: 400;
            font-size: 0.9rem;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid var(--glass-border);
            border-radius: 10px;
            color: var(--text-primary);
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: var(--text-accent);
            background: rgba(255, 255, 255, 0.15);
            box-shadow: 0 0 0 3px rgba(100, 255, 218, 0.2);
        }

        .btn {
            padding: 12px 24px;
            background: var(--gradient-secondary);
            border: none;
            border-radius: 25px;
            color: var(--text-primary);
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
            margin: 0 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-glow);
        }

        .btn-secondary {
            background: transparent;
            border: 1px solid var(--glass-border);
        }

        .close-btn {
            position: absolute;
            top: 15px;
            right: 20px;
            background: none;
            border: none;
            color: var(--text-secondary);
            font-size: 1.5rem;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .close-btn:hover {
            color: var(--text-primary);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .app-container {
                padding: 15px;
            }

            .progress-ring-container {
                width: 250px;
                height: 250px;
                margin: 40px auto;
            }

            .progress-percentage {
                font-size: 2.5rem;
            }

            .remaining-number {
                font-size: 3rem;
            }

            .countdown-grid {
                grid-template-columns: 1fr;
                gap: 15px;
                margin-top: 40px;
            }

            .settings-btn {
                top: 20px;
                right: 20px;
                width: 45px;
                height: 45px;
            }

            .modal-content {
                padding: 30px 20px;
            }
        }

        /* 动画效果 */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pulse {
            0%, 100% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
        }

        .fade-in {
            animation: fadeInUp 0.8s ease-out;
        }

        .pulse {
            animation: pulse 2s ease-in-out infinite;
        }
    </style>
</head>
<body>
    <!-- 星空背景 -->
    <div class="starry-background"></div>
    <div class="background-overlay"></div>

    <!-- 设置按钮 -->
    <div class="settings-btn" onclick="openSettings()">
        <svg viewBox="0 0 24 24">
            <path d="M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.22,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.22,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.68 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z"/>
        </svg>
    </div>

    <!-- 主容器 -->
    <div class="app-container">
        <div class="main-content fade-in">
            <!-- 标题区域 -->
            <div class="title-section">
                <h1 class="app-title">静谧的生命时钟</h1>
                <p class="app-subtitle">你已走过</p>
                <div class="quote-section">
                    <p class="quote" id="daily-quote">"时间是我们最宝贵的财富，因为它永远不会回来。"</p>
                    <button class="refresh-quote-btn" id="refresh-quote" title="刷新语录">🔄</button>
                </div>
            </div>

            <!-- 圆形进度环 -->
            <div class="progress-ring-container">
                <svg class="progress-ring" width="300" height="300">
                    <defs>
                        <linearGradient id="progressGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                            <stop offset="0%" style="stop-color:#ff6b35;stop-opacity:1" />
                            <stop offset="25%" style="stop-color:#f7931e;stop-opacity:1" />
                            <stop offset="50%" style="stop-color:#ffd23f;stop-opacity:1" />
                            <stop offset="75%" style="stop-color:#06ffa5;stop-opacity:1" />
                            <stop offset="100%" style="stop-color:#4dabf7;stop-opacity:1" />
                        </linearGradient>
                    </defs>
                    <circle class="progress-ring-bg" cx="150" cy="150" r="140"></circle>
                    <circle class="progress-ring-fill" cx="150" cy="150" r="140" id="progressCircle"></circle>
                </svg>
                <div class="progress-content">
                    <div class="progress-label">人生进度</div>
                    <div class="progress-percentage" id="lifePercentage">25.3%</div>
                    <div class="progress-sublabel">已度过的时光</div>
                </div>
            </div>

            <!-- 剩余时间显示 -->
            <div class="remaining-time">
                <div class="remaining-number pulse" id="remainingTime">20,075</div>
                <div class="unit-switcher">
                    <div class="unit-btn active" data-unit="days">天</div>
                    <div class="unit-btn" data-unit="months">月</div>
                    <div class="unit-btn" data-unit="years">年</div>
                    <div class="unit-btn" data-unit="hours">时</div>
                </div>
            </div>

            <!-- 倒计时卡片网格 -->
            <div class="countdown-grid">
                <div class="countdown-card fade-in">
                    <div class="card-icon">🌅</div>
                    <div class="card-title">今日倒计时</div>
                    <div class="card-progress">
                        <div class="card-progress-fill" id="todayProgress" style="width: 65%"></div>
                    </div>
                    <div class="card-number" id="todayHours">8.5</div>
                    <div class="card-unit">小时</div>
                </div>

                <div class="countdown-card fade-in">
                    <div class="card-icon">📅</div>
                    <div class="card-title">本周倒计时</div>
                    <div class="card-progress">
                        <div class="card-progress-fill" id="weekProgress" style="width: 42%"></div>
                    </div>
                    <div class="card-number" id="weekHours">98</div>
                    <div class="card-unit">小时</div>
                </div>

                <div class="countdown-card fade-in">
                    <div class="card-icon">🗓️</div>
                    <div class="card-title">本月倒计时</div>
                    <div class="card-progress">
                        <div class="card-progress-fill" id="monthProgress" style="width: 23%"></div>
                    </div>
                    <div class="card-number" id="monthHours">568</div>
                    <div class="card-unit">小时</div>
                </div>

                <div class="countdown-card fade-in">
                    <div class="card-icon">🎯</div>
                    <div class="card-title">本年倒计时</div>
                    <div class="card-progress">
                        <div class="card-progress-fill" id="yearProgress" style="width: 89%"></div>
                    </div>
                    <div class="card-number" id="yearHours">264</div>
                    <div class="card-unit">小时</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 设置模态框 -->
    <div id="settingsModal" class="modal">
        <div class="modal-content">
            <button class="close-btn" onclick="closeSettings()">&times;</button>
            <h2 class="modal-title">⚙️ 个人设置</h2>
            <form id="settingsForm">
                <div class="form-group">
                    <label for="birthDate" class="form-label">出生日期</label>
                    <input type="date" id="birthDate" name="birthDate" class="form-input" required>
                </div>
                <div class="form-group">
                    <label for="lifeExpectancy" class="form-label">预计寿命（岁）</label>
                    <input type="number" id="lifeExpectancy" name="lifeExpectancy" class="form-input" min="50" max="120" value="80" required>
                </div>
                <div style="text-align: center; margin-top: 30px;">
                    <button type="button" class="btn btn-secondary" onclick="closeSettings()">取消</button>
                    <button type="submit" class="btn">保存设置</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 全局变量
        let userSettings = {
            birthDate: '1990-01-01',
            lifeExpectancy: 80
        };

        let currentUnit = 'days';
        const circumference = 2 * Math.PI * 140;
        const API_BASE_URL = 'http://localhost:5000/api';

        // ===== 智能语录功能 =====

        /**
         * 检查本地缓存的语录是否仍然有效
         */
        function getCachedQuote() {
            try {
                const cachedQuote = localStorage.getItem('lifeCountdown_lastQuote');
                if (!cachedQuote) return null;
                
                const parsed = JSON.parse(cachedQuote);
                const now = Date.now();
                const cacheAge = now - parsed.timestamp;
                const maxAge = 6 * 60 * 60 * 1000; // 6小时，与后端保持一致
                
                // 如果缓存还在有效期内，直接使用
                if (cacheAge < maxAge) {
                    return {
                        success: true,
                        quote: parsed.quote,
                        source: 'local_cache',
                        age: Math.floor(cacheAge / (60 * 1000)) // 缓存年龄（分钟）
                    };
                }
                
                return null;
            } catch (error) {
                console.error('读取缓存语录失败:', error);
                return null;
            }
        }

        /**
         * 从后端API获取智能语录
         */
        async function fetchQuote() {
            try {
                const response = await fetch(`${API_BASE_URL}/quote`);
                const data = await response.json();
                
                if (data.success) {
                    // 保存到本地存储
                    localStorage.setItem('lifeCountdown_lastQuote', JSON.stringify({
                        quote: data.quote,
                        source: data.source,
                        timestamp: Date.now()
                    }));
                    
                    return data;
                } else {
                    throw new Error(data.error || '获取语录失败');
                }
            } catch (error) {
                console.error('获取语录失败:', error);
                
                // 尝试使用本地缓存的语录（即使过期也比没有好）
                const cachedQuote = localStorage.getItem('lifeCountdown_lastQuote');
                if (cachedQuote) {
                    const parsed = JSON.parse(cachedQuote);
                    return {
                        success: true,
                        quote: parsed.quote,
                        source: 'expired_cache'
                    };
                }
                
                // 返回默认语录
                return {
                    success: true,
                    quote: '每一天都是新的开始，充满无限可能。',
                    source: 'default'
                };
            }
        }

        /**
         * 更新语录显示
         */
        function updateQuoteDisplay(quote, source) {
            const quoteElement = document.getElementById('daily-quote');
            const refreshBtn = document.getElementById('refresh-quote');
            
            if (quoteElement) {
                // 添加淡出效果
                quoteElement.style.opacity = '0';
                
                setTimeout(() => {
                    quoteElement.textContent = `"${quote}"`;
                    
                    // 添加来源标识
                    if (source === 'deepseek') {
                        quoteElement.setAttribute('title', 'AI生成的智能语录');
                    } else if (source === 'cache') {
                        quoteElement.setAttribute('title', '缓存的语录');
                    } else {
                        quoteElement.setAttribute('title', '默认语录');
                    }
                    
                    // 淡入效果
                    quoteElement.style.opacity = '1';
                }, 300);
            }
            
            // 重新启用刷新按钮
            if (refreshBtn) {
                refreshBtn.disabled = false;
                refreshBtn.textContent = '🔄';
            }
        }

        /**
         * 刷新语录
         */
        async function refreshQuote() {
            const refreshBtn = document.getElementById('refresh-quote');
            
            if (refreshBtn) {
                refreshBtn.disabled = true;
                refreshBtn.textContent = '⏳';
            }
            
            try {
                const data = await fetchQuote();
                updateQuoteDisplay(data.quote, data.source);
                console.log('语录刷新成功:', data);
            } catch (error) {
                console.error('刷新语录失败:', error);
                if (refreshBtn) {
                    refreshBtn.disabled = false;
                    refreshBtn.textContent = '🔄';
                }
            }
        }

        /**
         * 初始化语录功能
         */
        async function initQuote() {
            try {
                // 首先检查本地缓存
                const cachedQuote = getCachedQuote();
                
                if (cachedQuote) {
                    // 使用缓存的语录，避免不必要的API调用
                    console.log(`使用缓存语录，缓存年龄: ${cachedQuote.age}分钟`);
                    updateQuoteDisplay(cachedQuote.quote, cachedQuote.source);
                } else {
                    // 缓存不存在或已过期，从API获取新语录
                    console.log('缓存已过期或不存在，从API获取新语录');
                    const data = await fetchQuote();
                    updateQuoteDisplay(data.quote, data.source);
                }
                
                // 绑定刷新按钮事件
                const refreshBtn = document.getElementById('refresh-quote');
                if (refreshBtn) {
                    refreshBtn.addEventListener('click', refreshQuote);
                }
            } catch (error) {
                console.error('初始化语录功能失败:', error);
                // 如果所有方法都失败，显示默认语录
                updateQuoteDisplay('每一天都是新的开始，充满无限可能。', 'default');
            }
        }

        // 初始化应用
        function initApp() {
            loadSettings();
            updateAllCountdowns();
            setInterval(updateAllCountdowns, 1000);
            setupEventListeners();
            // 初始化语录功能
            initQuote();
        }

        // 加载设置
        function loadSettings() {
            const saved = localStorage.getItem('lifeCountdownSettings');
            if (saved) {
                userSettings = JSON.parse(saved);
            }
            document.getElementById('birthDate').value = userSettings.birthDate;
            document.getElementById('lifeExpectancy').value = userSettings.lifeExpectancy;
        }

        // 保存设置
        function saveSettings() {
            localStorage.setItem('lifeCountdownSettings', JSON.stringify(userSettings));
        }

        // 设置事件监听器
        function setupEventListeners() {
            // 单位切换器
            document.querySelectorAll('.unit-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.unit-btn').forEach(b => b.classList.remove('active'));
                    this.classList.add('active');
                    currentUnit = this.dataset.unit;
                    updateRemainingTime();
                });
            });

            // 表单提交
            document.getElementById('settingsForm').addEventListener('submit', function(e) {
                e.preventDefault();
                userSettings.birthDate = document.getElementById('birthDate').value;
                userSettings.lifeExpectancy = parseInt(document.getElementById('lifeExpectancy').value);
                saveSettings();
                updateAllCountdowns();
                closeSettings();
            });

            // 模态框外部点击关闭
            document.getElementById('settingsModal').addEventListener('click', function(e) {
                if (e.target === this) {
                    closeSettings();
                }
            });
        }

        // 计算年龄和剩余时间
        function calculateLifeStats() {
            const now = new Date();
            const birth = new Date(userSettings.birthDate);
            const lifeEnd = new Date(birth.getTime() + userSettings.lifeExpectancy * 365.25 * 24 * 60 * 60 * 1000);
            
            const totalLifeMs = lifeEnd.getTime() - birth.getTime();
            const livedMs = now.getTime() - birth.getTime();
            const remainingMs = lifeEnd.getTime() - now.getTime();
            
            const lifePercentage = (livedMs / totalLifeMs) * 100;
            
            return {
                lifePercentage: Math.max(0, Math.min(100, lifePercentage)),
                remainingDays: Math.max(0, Math.ceil(remainingMs / (1000 * 60 * 60 * 24))),
                remainingMonths: Math.max(0, Math.ceil(remainingMs / (1000 * 60 * 60 * 24 * 30.44))),
                remainingYears: Math.max(0, Math.ceil(remainingMs / (1000 * 60 * 60 * 24 * 365.25))),
                remainingHours: Math.max(0, Math.ceil(remainingMs / (1000 * 60 * 60)))
            };
        }

        // 更新圆形进度环
        function updateProgressRing(percentage) {
            const circle = document.getElementById('progressCircle');
            const offset = circumference - (percentage / 100) * circumference;
            circle.style.strokeDasharray = `${circumference} ${circumference}`;
            circle.style.strokeDashoffset = offset;
        }

        // 更新剩余时间显示
        function updateRemainingTime() {
            const stats = calculateLifeStats();
            const remainingTimeEl = document.getElementById('remainingTime');
            
            let value;
            switch(currentUnit) {
                case 'days':
                    value = stats.remainingDays.toLocaleString();
                    break;
                case 'months':
                    value = stats.remainingMonths.toLocaleString();
                    break;
                case 'years':
                    value = stats.remainingYears.toLocaleString();
                    break;
                case 'hours':
                    value = stats.remainingHours.toLocaleString();
                    break;
            }
            
            remainingTimeEl.textContent = value;
        }

        // 更新基础倒计时卡片
        function updateBasicCountdowns() {
            const now = new Date();
            
            // 今日倒计时
            const endOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            const todayRemaining = endOfDay.getTime() - now.getTime();
            const todayHours = todayRemaining / (1000 * 60 * 60);
            const todayProgress = ((24 - todayHours) / 24) * 100;
            
            document.getElementById('todayHours').textContent = todayHours.toFixed(1);
            document.getElementById('todayProgress').style.width = `${todayProgress}%`;
            
            // 本周倒计时
            const dayOfWeek = now.getDay();
            const daysUntilSunday = dayOfWeek === 0 ? 0 : 7 - dayOfWeek;
            const endOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() + daysUntilSunday + 1);
            const weekRemaining = endOfWeek.getTime() - now.getTime();
            const weekHours = weekRemaining / (1000 * 60 * 60);
            const weekProgress = ((168 - weekHours) / 168) * 100;
            
            document.getElementById('weekHours').textContent = Math.ceil(weekHours);
            document.getElementById('weekProgress').style.width = `${weekProgress}%`;
            
            // 本月倒计时
            const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
            const monthRemaining = endOfMonth.getTime() - now.getTime();
            const monthHours = monthRemaining / (1000 * 60 * 60);
            const daysInMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
            const monthProgress = ((daysInMonth * 24 - monthHours) / (daysInMonth * 24)) * 100;
            
            document.getElementById('monthHours').textContent = Math.ceil(monthHours);
            document.getElementById('monthProgress').style.width = `${monthProgress}%`;
            
            // 本年倒计时
            const endOfYear = new Date(now.getFullYear() + 1, 0, 1);
            const yearRemaining = endOfYear.getTime() - now.getTime();
            const yearHours = yearRemaining / (1000 * 60 * 60);
            const yearProgress = ((8760 - yearHours) / 8760) * 100;
            
            document.getElementById('yearHours').textContent = Math.ceil(yearHours);
            document.getElementById('yearProgress').style.width = `${yearProgress}%`;
        }

        // 更新所有倒计时
        function updateAllCountdowns() {
            const stats = calculateLifeStats();
            
            // 更新人生进度
            document.getElementById('lifePercentage').textContent = `${stats.lifePercentage.toFixed(1)}%`;
            updateProgressRing(stats.lifePercentage);
            
            // 更新剩余时间
            updateRemainingTime();
            
            // 更新基础倒计时
            updateBasicCountdowns();
        }

        // 打开设置模态框
        function openSettings() {
            document.getElementById('settingsModal').style.display = 'flex';
        }

        // 关闭设置模态框
        function closeSettings() {
            document.getElementById('settingsModal').style.display = 'none';
        }

        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeSettings();
            }
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>